#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一异常处理器
提供异常捕获、记录和响应功能
"""

import logging
import traceback
from typing import Optional, Dict, Any
from datetime import datetime
from .base_exceptions import BrainWaveException

class ExceptionHandler:
    """统一异常处理器"""
    
    def __init__(self, logger_name: str = "brain_wave"):
        self.logger = logging.getLogger(logger_name)
    
    def handle_exception(self, exception: Exception, context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """处理异常并返回标准化响应
        
        Args:
            exception: 异常对象
            context: 异常上下文信息
            
        Returns:
            标准化的异常响应字典
        """
        context = context or {}
        
        # 记录异常
        self._log_exception(exception, context)
        
        # 生成响应
        if isinstance(exception, BrainWaveException):
            return self._handle_custom_exception(exception, context)
        else:
            return self._handle_system_exception(exception, context)
    
    def _log_exception(self, exception: Exception, context: Dict[str, Any]):
        """记录异常信息"""
        error_info = {
            "timestamp": datetime.now().isoformat(),
            "exception_type": type(exception).__name__,
            "message": str(exception),
            "context": context,
            "traceback": traceback.format_exc()
        }
        
        if isinstance(exception, BrainWaveException):
            error_info.update({
                "error_code": exception.error_code,
                "details": exception.details
            })
        
        self.logger.error(f"Exception occurred: {error_info}")
    
    def _handle_custom_exception(self, exception: BrainWaveException, context: Dict[str, Any]) -> Dict[str, Any]:
        """处理自定义异常"""
        response = exception.to_dict()
        response.update({
            "success": False,
            "timestamp": datetime.now().isoformat(),
            "context": context
        })
        return response
    
    def _handle_system_exception(self, exception: Exception, context: Dict[str, Any]) -> Dict[str, Any]:
        """处理系统异常"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        detailed_message = f"[{timestamp}] 系统内部错误: {str(exception)}"
        
        return {
            "success": False,
            "error_code": "SYSTEM_ERROR",
            "message": detailed_message,
            "details": {
                "exception_type": type(exception).__name__,
                "original_message": str(exception),
                "timestamp": timestamp
            },
            "timestamp": datetime.now().isoformat(),
            "context": context
        }

def exception_handler_decorator(handler: ExceptionHandler = None, context_func=None):
    """异常处理装饰器
    
    Args:
        handler: 异常处理器实例
        context_func: 获取上下文信息的函数
    """
    if handler is None:
        handler = ExceptionHandler()
    
    def decorator(func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                context = {}
                if context_func:
                    try:
                        context = context_func(*args, **kwargs)
                    except:
                        pass
                
                context.update({
                    "function": func.__name__,
                    "args": str(args)[:200],  # 限制长度
                    "kwargs": str(kwargs)[:200]
                })
                
                error_response = handler.handle_exception(e, context)
                raise BrainWaveException(
                    error_response["message"],
                    error_response["error_code"],
                    error_response["details"]
                )
        return wrapper
    return decorator

# 全局异常处理器实例
global_exception_handler = ExceptionHandler()